import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'dart:convert';
import 'package:toast/toast.dart';
import 'package:shared_preferences/shared_preferences.dart';

/*
 * 封装 restful 请求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class DioUtil {
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'http://admin.inssuper.com/super-server/';
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  ///Get请求测试
  static void getHttp() async {
    try {
      Response response = await Dio().get("http://www.google.cn");
      print("response$response");
    } catch (e) {
      print(e);
    }
  }

  static Future<String> getStore(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(key);
  }

  ///Post请求测试
  static void postHttp<T>(
      String url, {
        params,
        Function(T t) onSuccess,
        BuildContext buildContext,
        Function(String error) onError,
      }) async {

    ///定义请求参数
    params = params ?? {};
    //参数处理
    params.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    Future<String> userId = getStore("userId");
    userId.then((String uid){
      if(uid!=null && uid!=''){
        params['crteMngId'] = uid;
      }
    });


    try {
      Response response;
      Dio dio = createInstance();
      response = await dio.post(url, data: params);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          if(response.data!=null){
            print(response.data);
            Map<String, dynamic> result = jsonDecode(response.data);
            print(result['code']);
            if(result['code'] != 0){
              Toast.show(result['msg'],buildContext);
            }
            onSuccess(response.data);
          }
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }
  }

  /// request method
  //url 请求链接
  //params 请求参数
  //metthod 请求方式
  //onSuccess 成功回调
  //onError 失败回调
  static Future<Map> request<T>(String url,
      {params,
        method,
        Function(T t) onSuccess,
        Function(String error) onError}) async {
    params = params ?? {};
    method = method ?? 'GET';

    /// 请求处理
    params.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印:请求地址-请求方式-请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + params.toString());

    Dio dio = createInstance();
    //请求结果
    var result;
    try {
      Response response = await dio.request(url,
          data: params, options: new Options(method: method,headers: {
            "Authorization":"bearer;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImppYW5zaHVpIiwidXNlcmlkIjoxMiwiaXNzIjoic3VwZXIiLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU4Njc2MjI3NiwibmJmIjoxNTg2NTg5NDc2fQ.lYVEs4O9TqUExF7NT57D4w12r-JZzEWmqyLU97zAzJw",
            "from_key":"wx_mini"
          }));
      result = response.data;
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(result);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }

    return result;
  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      var options = BaseOptions(
        connectTimeout: 15000,
        receiveTimeout: 15000,
        responseType: ResponseType.plain,
        validateStatus: (status) {
          // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
          return true;
        },
        baseUrl: "http://admin.inssuper.com/super-server/",
        headers: {
          "from_key":"wx_mini",
          "Authorization":"bearer;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImppYW5zaHVpIiwidXNlcmlkIjoxMiwiaXNzIjoic3VwZXIiLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU4Njc2MjI3NiwibmJmIjoxNTg2NTg5NDc2fQ.lYVEs4O9TqUExF7NT57D4w12r-JZzEWmqyLU97zAzJw"
        }
      );

      dio = new Dio(options);
    }

    return dio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }
}